package cn.itcast.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 演示粘包和半包现象
 * @Date 2021/7/19
 * @Created by Jonathan
 */
@Slf4j
public class HelloWorldClient {
    public static void main(String[] args) {
        send();
        /*for (int i = 0; i < 10; i++) {
            send();
            log.info("finished!");
        }*/
    }

    public static void send() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(worker);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        // 连上服务器会触发这个函数
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            log.info("hello world client");
                            //for (int i = 0; i < 10; i++) {
                            ByteBuf buffer = ctx.alloc().buffer(18);
                            buffer.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18});
                            ctx.writeAndFlush(buffer);
                            ctx.channel().close();
                            //}

                        }
                    });
                }
            });
            ChannelFuture localhost = bootstrap.connect("127.0.0.1", 8080).sync();
            localhost.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
